/*
一个游戏服务器,一个游戏的方式
服务启动后,调用 initAndStartGame 初始化游戏

*/
import { InputType } from "../shared/gameClient/protocols/SimpleFrameSyncGame";

import { GameMsgCall } from "../api/base";
import { Game } from "../Game";
import { onConnAuthed } from "../gameConnMgr";
import { gameServer } from "../server";
import { MsgInpFrame } from "../shared/gameClient/protocols/MsgInpFrame";

/**当前游戏服务器范围的游戏实例,需要服务启动后调用 initAndStartGame(...) */
let globalGame: Game;

/**
 * 初始化和启动全局游戏
 * @param [syncFrameRate] 
 */
function initAndStartGlobalGame(syncFrameRate = 60) {
    globalGame = new Game(syncFrameRate);

    onConnAuthed(conn => {
        if (globalGame.connections.length <= 0) {
            //如果这连接是第一个,则启动游戏
            globalGame.startGame();
        }
        //连接加入游戏
        globalGame.addConnection(conn);
        //发送追帧数据
        globalGame.connectionAfterFrames(conn);
        //自动插入一个新增玩家的输入
        globalGame.addConnectionInpFrame(conn.connectionId, {
            operates: [
                {
                    inputType: InputType.NewPlayer,
                    userName: conn.userInfo.userName,
                }
            ]
        });
    });
    gameServer.flows.postDisconnectFlow.push(async v => {
        globalGame.removeConnection(v.conn.connectionId);
        if (globalGame.connections.length <= 0) {
            //如果没有连接了,则停止游戏
            globalGame.stopGame();
        }
        if (!v.conn.userInfo) {
            //如果未登录,则忽略
            return v;
        }
        //自动插入一个移出玩家的输入
        globalGame.addConnectionInpFrame(v.conn.connectionId, {
            operates: [
                { inputType: InputType.RemovePlayer }
            ]
        });
        return v;
    });
    gameServer.listenMsg('InpFrame', (call: GameMsgCall<MsgInpFrame>) => {
        globalGame.addConnectionInpFrame(call.conn.connectionId, call.msg);
    });
}



export {
    initAndStartGlobalGame,
    globalGame,
};
